package com.tgy.algorithm.base._单调栈;

import java.util.Arrays;
import java.util.Stack;

public class _获取数组每一个位置最近的小于当前值 {

    public static int[][] getLtVals(int[] nums) {

        int len = nums.length;
        if (nums == null || len == 0) {
            return null;
        }

        int[][] rets = new int[len][2];
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < len; i++) {
            int value = nums[i];
            while (!stack.isEmpty() && nums[stack.peek()] > value) {
                Integer preIndex = stack.pop();
                rets[preIndex][0] = stack.isEmpty()?-1:stack.peek();
                rets[preIndex][1] = i;
            }
            stack.push(i);
        }

        while (!stack.isEmpty()) {
            Integer preIndex = stack.pop();
            if (stack.isEmpty()) {
                rets[preIndex][0] = -1;
            }else {
                rets[preIndex][0] = nums[stack.peek()] != nums[preIndex]?stack.peek():-1;
            }
            rets[preIndex][1] = -1;
        }

        return rets;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{3,2,4,2,3,2,3};
        int[][] ltVals = getLtVals(nums);
        for (int[] ltVal : ltVals) {
            System.out.println(Arrays.toString(ltVal));
        }
    }
}
